// 智能童话书增强版 - JavaScript 功能模块

// 故事生成表单处理
document.getElementById('storyForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    // 显示加载状态
    document.getElementById('welcomeMessage').style.display = 'none';
    document.getElementById('storyContent').style.display = 'none';
    document.getElementById('loadingMessage').style.display = 'block';
    
    // 收集表单数据
    const formData = {
        theme: document.getElementById('theme').value,
        characters: document.getElementById('characters').value.split(',').map(s => s.trim()),
        age_group: document.getElementById('ageGroup').value,
        emotional_focus: 'friendship',
        story_length: 'medium',
        interaction_level: 'high'
    };
    
    try {
        // 发送请求到API
        const response = await fetch('/api/generate_story', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData)
        });
        
        const result = await response.json();
        
        // 隐藏加载状态
        document.getElementById('loadingMessage').style.display = 'none';
        
        if (result.success) {
            displayEnhancedStory(result.data);
        } else {
            displayError(result.message || '故事生成失败');
        }
        
    } catch (error) {
        document.getElementById('loadingMessage').style.display = 'none';
        console.error('Error:', error);
        displayError('网络错误，请稍后重试');
    }
});

function displayEnhancedStory(storyData) {
    const storyContent = document.getElementById('storyContent');
    
    let html = `
        <div class="story-header mb-4 text-center">
            <h2 class="text-primary mb-3">
                <i class="bi bi-book"></i> ${storyData.title}
            </h2>
        </div>
        
        <div class="story-text mb-4">
            <h5><i class="bi bi-journal-text"></i> 故事内容</h5>
            <div class="story-body p-4" style="background: #f8f9fa; border-radius: 10px; line-height: 1.8; font-size: 1.1em;">
                ${storyData.story.replace(/\n\n/g, '</p><p>').replace(/^/, '<p>').replace(/$/, '</p>')}
            </div>
        </div>`;
    
    // 显示角色信息
    if (storyData.characters && storyData.characters.length > 0) {
        html += `
            <div class="characters-info mb-4">
                <h5><i class="bi bi-people"></i> 角色信息</h5>
                <div class="row">`;
        
        storyData.characters.forEach(char => {
            html += `
                <div class="col-md-6 mb-2">
                    <div class="character-card p-3" style="background: linear-gradient(45deg, #0dcaf0, #20c997); color: white; border-radius: 10px;">
                        <strong>${char.name}</strong>
                        <br><small>${char.traits ? char.traits.join(', ') : '善良、勇敢'}</small>
                    </div>
                </div>`;
        });
        
        html += `</div></div>`;
    }
    
    // 显示教育洞察
    if (storyData.educational_insights && storyData.educational_insights.length > 0) {
        html += `
            <div class="educational-insights mb-4">
                <h5><i class="bi bi-lightbulb"></i> 教育价值</h5>
                <ul class="list-group">`;
        
        storyData.educational_insights.forEach(insight => {
            html += `<li class="list-group-item"><i class="bi bi-check-circle text-success"></i> ${insight}</li>`;
        });
        
        html += `</ul></div>`;
    }
    
    // 显示质量评分
    if (storyData.quality_score) {
        const score = Math.round(storyData.quality_score.overall * 100);
        html += `
            <div class="quality-score mb-4 text-center">
                <div class="score-badge p-3" style="background: linear-gradient(135deg, #ffc107, #fd7e14); color: white; border-radius: 15px; display: inline-block;">
                    <h4>📊 故事质量评分</h4>
                    <h2>${score}分</h2>
                    <small>基于AI智能分析</small>
                </div>
            </div>`;
    }
    
    // 添加评分区域
    html += `
        <div class="rating-section text-center mt-4 p-4" style="background: #e3f2fd; border-radius: 10px;">
            <h5><i class="bi bi-star"></i> 为这个故事评分</h5>
            <div class="star-rating mb-3">
                <button class="btn btn-outline-warning star-btn" data-rating="1">⭐</button>
                <button class="btn btn-outline-warning star-btn" data-rating="2">⭐⭐</button>
                <button class="btn btn-outline-warning star-btn" data-rating="3">⭐⭐⭐</button>
                <button class="btn btn-outline-warning star-btn" data-rating="4">⭐⭐⭐⭐</button>
                <button class="btn btn-outline-warning star-btn" data-rating="5">⭐⭐⭐⭐⭐</button>
            </div>
            <button class="btn btn-primary" onclick="generateNewStory()">
                <i class="bi bi-arrow-clockwise"></i> 生成新故事
            </button>
        </div>`;
    
    storyContent.innerHTML = html;
    storyContent.style.display = 'block';
    
    // 添加评分事件监听器
    document.querySelectorAll('.star-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const rating = parseInt(this.dataset.rating);
            submitRating(rating, storyData.title);
        });
    });
}

function displayError(message) {
    const storyContent = document.getElementById('storyContent');
    storyContent.innerHTML = `
        <div class="alert alert-danger text-center">
            <i class="bi bi-exclamation-triangle"></i>
            <h4>出现错误</h4>
            <p>${message}</p>
            <button class="btn btn-outline-danger" onclick="location.reload()">
                <i class="bi bi-arrow-clockwise"></i> 重新加载
            </button>
        </div>`;
    storyContent.style.display = 'block';
}

function generateNewStory() {
    document.getElementById('welcomeMessage').style.display = 'block';
    document.getElementById('storyContent').style.display = 'none';
    document.getElementById('loadingMessage').style.display = 'none';
}

async function submitRating(rating, storyTitle) {
    try {
        const response = await fetch('/api/rate_story', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                rating: rating,
                story_id: storyTitle,
                feedback: `用户给出${rating}星评价`
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert(`感谢您的评分！给出了${rating}颗星 ⭐`);
            // 更新统计信息
            document.getElementById('averageRating').textContent = result.average_rating;
        }
        
    } catch (error) {
        console.error('评分提交失败:', error);
        alert('评分提交失败，请稍后重试');
    }
}

// 定期更新系统状态
setInterval(async function() {
    try {
        const response = await fetch('/api/system_status');
        const status = await response.json();
        
        // 更新统计信息
        document.getElementById('totalStories').textContent = status.total_stories || 0;
        document.getElementById('userSessions').textContent = status.user_sessions || 0;
        document.getElementById('averageRating').textContent = status.average_rating || '0.0';
        document.getElementById('systemStatus').textContent = status.system_status === '运行正常' ? '🟢' : '🔴';
        
    } catch (error) {
        console.error('状态更新失败:', error);
    }
}, 30000); // 每30秒更新一次